import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getKpiData, getTrendData, getCategoryData, getSupplierData, getModelTrend } from '../api/anr'

export const useAnrStore = defineStore('anr', () => {
  // 状态
  const loading = ref(false)
  const timeRange = ref('week') // week, month, custom
  const customDateRange = ref([])
  const selectedModels = ref([])
  const modelTrendPeriod = ref('month') // 'month' | 'week'

  // KPI（不含修复率）
  const kpiData = ref({
    weeklyIssues: 0,
    monthlyIssues: 0,
    recurrenceRate: 0,
    topModel: '暂无数据'
  })

  // 趋势数据
  const trendData = ref({
    timeSeries: { legend: [], xAxis: [], series: [] },
    modelStack: { legend: [], xAxis: [], series: [] },
    heatmap: { xAxis: [], yAxis: [], series: [] }
  })

  // 型号-时间趋势（月/周）
  const modelTrendData = ref({ legend: [], xAxis: [], series: [] })

  // 分类数据（不含修复率仪表盘）
  const categoryData = ref({
    problemCategory: { series: [] },
    initialScreening: { series: [] }
  })

  // 供应商数据
  const supplierData = ref({
    sankey: { series: [] },
    wordCloud: { series: [] }
  })

  // 文案
  const timeRangeText = computed(() => {
    switch (timeRange.value) {
      case 'week': return '本周'
      case 'month': return '本月'
      case 'custom': return '自定义'
      default: return '本周'
    }
  })

  // 加载
  const loadInitialData = async () => {
    loading.value = true
    try {
      await Promise.all([
        loadKpiData(),
        loadTrendData(),
        loadModelTrendData(),
        loadCategoryData(),
        loadSupplierData()
      ])
    } catch (error) {
      console.error('初始化数据失败:', error)
    } finally {
      loading.value = false
    }
  }

  const loadKpiData = async () => {
    try {
      const data = await getKpiData({
        timeRange: timeRange.value,
        customDateRange: customDateRange.value,
        models: selectedModels.value
      })
      kpiData.value = data
    } catch (error) {
      console.error('获取KPI数据失败:', error)
    }
  }

  const loadTrendData = async () => {
    try {
      const data = await getTrendData({
        timeRange: timeRange.value,
        customDateRange: customDateRange.value,
        models: selectedModels.value
      })
      trendData.value = data
    } catch (error) {
      console.error('获取趋势数据失败:', error)
    }
  }

  const loadModelTrendData = async () => {
    try {
      // 需求：按月查看应展示全量（月度不受顶部时间筛选限制）；按周遵循顶部时间筛选
      const useAllForMonth = modelTrendPeriod.value === 'month'
      const params = {
        models: selectedModels.value,
        period: modelTrendPeriod.value
      }
      if (!useAllForMonth) {
        params.timeRange = timeRange.value
        params.customDateRange = customDateRange.value
      }
      const data = await getModelTrend(params)
      modelTrendData.value = data || { legend: [], xAxis: [], series: [] }
    } catch (error) {
      console.error('获取型号时间趋势失败:', error)
      modelTrendData.value = { legend: [], xAxis: [], series: [] }
    }
  }

  const loadCategoryData = async () => {
    try {
      const data = await getCategoryData({
        timeRange: timeRange.value,
        customDateRange: customDateRange.value,
        models: selectedModels.value
      })
      categoryData.value = data
    } catch (error) {
      console.error('获取分类数据失败:', error)
    }
  }

  const loadSupplierData = async () => {
    try {
      const data = await getSupplierData({
        timeRange: timeRange.value,
        customDateRange: customDateRange.value,
        models: selectedModels.value
      })
      supplierData.value = data
    } catch (error) {
      console.error('获取供应商数据失败:', error)
    }
  }

  const refreshAllData = async () => {
    await loadInitialData()
  }

  const setTimeRange = (range) => {
    timeRange.value = range
    refreshAllData()
  }

  const setCustomDateRange = (range) => {
    customDateRange.value = range
    if (timeRange.value === 'custom') {
      refreshAllData()
    }
  }

  const setSelectedModels = (models) => {
    selectedModels.value = models
    refreshAllData()
  }

  const setModelTrendPeriod = (p) => {
    modelTrendPeriod.value = p
    loadModelTrendData()
  }

  return {
    // 状态
    loading,
    timeRange,
    customDateRange,
    selectedModels,
    modelTrendPeriod,
    kpiData,
    trendData,
    modelTrendData,
    categoryData,
    supplierData,

    // 文案
    timeRangeText,

    // 加载
    loadInitialData,
    loadKpiData,
    loadTrendData,
    loadModelTrendData,
    loadCategoryData,
    loadSupplierData,
    refreshAllData,
    setTimeRange,
    setCustomDateRange,
    setSelectedModels,
    setModelTrendPeriod
  }
})
